/**
 * @author
 * @createtime
 * @class ProjectReceiveForm
 * @extends Ext.Window
 * @description ProjectReceive表单
 */
ProjectReceiveForm = Ext.extend(Ext.Window, {
	//内嵌FormPanel
	formPanel : null,
	//构造函数
	constructor : function(_cfg) {
		Ext.applyIf(this, _cfg);
		//必须先初始化组件
		this.initUIComponents();
		ProjectReceiveForm.superclass.constructor.call(this, {
			id : 'ProjectReceiveFormWin',
			layout : 'fit',
			items : this.formPanel,
			modal : true,
			width : 750,
			height : 470,
			maximizable : false,
			title : '[工程项目收款登记]详细信息',
			buttonAlign : 'center',
			buttons : this.buttons
		});
	},//end of the constructor
	//初始化组件
	initUIComponents : function() {
		var thizId = this.id;
		this.formPanel = new Ext.FormPanel({
			layout : 'form',
			trackResetOnLoad : true,
			bodyStyle : 'padding:10px 10px 10px 10px',
			border : false,
			url : __ctxPath + '/project/saveProjectReceive.do',
			id : 'ProjectReceiveForm',
			defaults : {
				anchor : '98%,98%'
			},
			defaultType : 'textfield',
			items : [{
						name : 'projectReceive.id',
						id : 'id',
						xtype : 'hidden',
						value : this.id == null ? '' : this.id
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '项目名称：',
									width : 60
								}, {
									xtype : 'textfield',
									name : 'projectReceiveProName',
									id : 'projectReceiveProName',
									columnWidth : .6,
									maxLength : 64,
									allowBlank : false,
									emptyText : '请选择项目',
									listeners : {
										'focus' : function() {
											ProjectSelector.getView(function(proId, proName, proNo,contractAmount) {
												Ext.getCmp("projectReceive.project.id").setValue(proId);
												Ext.getCmp("projectReceiveProName").setValue(proName);
												Ext.getCmp("projectReceiveContractAmount").setValue(contractAmount);
											}, true).show();
										}
									}
								}, {
									xtype : "hidden",
									name : "projectReceive.project.id",
									id : "projectReceive.project.id"
								}, {
									text : '合同额(元)：',
									style : 'margin-left:10px;',
									width : 90
								}, {
									xtype : 'textfield',
									name : 'projectReceiveContractAmount',
									id : 'projectReceiveContractAmount',
									columnWidth : .3,
									readOnly : true
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '建设单位：',
									width : 60
								}, {
									xtype : 'textfield',
									name : 'projectReceive.constructionUnit',
									id : 'constructionUnit',
									allowBlank : false,
									maxLength : 64,
									columnWidth : .6
								}, {
									text : '施工单位：',
									style : 'margin-left:10px;',
									width : 90
								}, {
									xtype : 'textfield',
									name : 'projectReceive.workUnit',
									maxLength : 64,
									allowBlank : false,
									id : 'workUnit',
									columnWidth : .3
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '工程所在地税局地址：',
									width : 135
								}, {
									xtype : 'textfield',
									name : 'projectReceive.taxLocation',
									id : 'taxLocation',
									allowBlank : false,
									maxLength : 64,
									columnWidth : .54
								}, {
									text : '联系方式：',
									style : 'margin-left:10px;',
									width : 90
								}, {
									xtype : 'textfield',
									name : 'projectReceive.contact',
									id : 'contact',
									allowBlank : false,
									maxLength : 64,
									columnWidth : .35
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '外经证期限：',
									width : 135
								}, {
									xtype : 'datefield',
									name : 'projectReceive.beginSignDate',
									id : 'beginSignDate',
									allowBlank : false,
									columnWidth : .27,
									format : 'Y-m-d'
								}, {
									text : '---'
								}, {
									xtype : 'datefield',
									name : 'projectReceive.endSignDate',
									id : 'endSignDate',
									allowBlank : false,
									columnWidth : .26,
									format : 'Y-m-d'
								}, {
									text : '实际税率(%)：',
									style : 'margin-left:10px;',
									width : 90
								}, {
									xtype : 'numberfield',
									name : 'projectReceive.actualTax',
									id : 'actualTax',
									allowBlank : false,
									maxLength : 5,
									columnWidth : .35
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '收款详情：'
								}, {
									style : 'color:red',
									id : 'projectReceiveErrorLabel',
									text : '(*必填)'
								}]
					}, {
						xtype : 'container',
						style : 'padding-left:0px;margin-bottom:10px',
						layout : 'column',
						items : [{
									name : 'receiveRegInfoDataList',
									xtype : 'hidden',
									id : 'receiveRegInfoDataList'
								}, {
									xtype : 'grid',
									id : 'projectReceive.resultGridDataGrid',
									height : 220,
									width : '98%',
									stripeRows : true,
									trackMouseOver : true,
									clicksToEdit : 1,
									plugins : [new Ext.ux.grid.RowEditor({
										saveText : '保存',
										cancelText : '取消',
										errorText : '请输入完整信息',
										errorSummary : false
									})],
									store : new Ext.data.JsonStore({
										url : __ctxPath + '/project/listProjectReceiveInfo.do',
										root : 'result',
										totalProperty : 'totalCounts',
										remoteSort : true,
										fields : ['id', 'billDate', 'billAmount', 'receiveDate', 'receiveAmount', 'leftAmount',{name:'operatorId',mapping:'operator.userId'},{name:'operatorName',mapping:'operator.fullname'}, 'remark'],
										listeners : {
											'update' : function(value) {
												var r = this.getRange();
												var jsonArr = [];
												var sum = 0;
												var rlen = r.length;
												for (var i = 0; i < rlen; i++) {
													if (r[i].fields) {
														var fields = r[i].fields;
														var flen = fields.length;
														var projectReceiveInfo = {
															id : null,
															billDate : '',
															billAmount : '',
															receiveDate : '',
															receiveAmount : '',
															leftAmount : '',
															operator : {
																userId : ''
															},
															remark : ''
														}
														for (var z = 0; z < flen; z++) {
															var fieldValue = r[i].get(fields.keys[z]);
															if (Ext.isEmpty(fieldValue)||fieldValue == '请双击选择' || fieldValue == '请双击填写' ) {
																continue;
															}
															if (fields.keys[z] == 'id') {
																if (fieldValue != '') {
																	projectReceiveInfo.id = fieldValue;
																}
															} else if (fields.keys[z] == 'billDate') {
																if (fieldValue != '') {
																	projectReceiveInfo.billDate = FormatGMTtoLocal(fieldValue, "yyyy-MM-dd");
																} else {
																	projectReceiveInfo.billDate = fieldValue;
																}
															} else if (fields.keys[z] == 'billAmount') {
																projectReceiveInfo.billAmount = fieldValue;
															} else if (fields.keys[z] == 'receiveDate') {
																if (fieldValue != '') {
																	projectReceiveInfo.receiveDate = FormatGMTtoLocal(fieldValue, "yyyy-MM-dd");
																} else {
																	projectReceiveInfo.receiveDate = fieldValue;
																}
															} else if (fields.keys[z] == 'receiveAmount') {
																projectReceiveInfo.receiveAmount = fieldValue;
															} else if (fields.keys[z] == 'leftAmount') {
																projectReceiveInfo.leftAmount = fieldValue;
															} else if (fields.keys[z] == 'operatorId') {
																projectReceiveInfo.operator.userId = fieldValue;
															} else if (fields.keys[z] == 'remark') {
																projectReceiveInfo.remark = fieldValue;
															}
														}
														jsonArr.push(projectReceiveInfo);
													}
												}
												Ext.getCmp('receiveRegInfoDataList').setValue(Ext.util.JSON.encode(jsonArr));
											}
										}
									}),
									cm : new Ext.grid.ColumnModel({
										columns : [new Ext.grid.RowNumberer(), {
													dataIndex : 'id',
													width : 50,
													hidden : true
												}, {
													header : '开票日期',
													dataIndex : 'billDate',
													editor : new Ext.grid.GridEditor(new Ext.form.DateField({
														allowBlank : false,
														id : 'billDate',
														format : 'Y-m-d'
													})),
													renderer : function(value) {
														if (value == '') {
															return '';
														} else if (typeof value == "string") {
															return value;
														} else {
															return formatDate(value, 'yyyy-MM-dd');
														}
													}
												}, {
													header : '开票金额(元)',
													dataIndex : 'billAmount',
													editor : new Ext.grid.GridEditor(new Ext.form.TextField({
														id : 'billAmount',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '到款日期',
													dataIndex : 'receiveDate',
													editor : new Ext.grid.GridEditor(new Ext.form.DateField({
														allowBlank : false,
														id : 'receiveDate',
														format : 'Y-m-d'
													})),
													renderer : function(value) {
														if (value == '') {
															return '';
														} else if (typeof value == "string") {
															return value;
														} else {
															return formatDate(value, 'yyyy-MM-dd');
														}
													}
												}, {
													header : '到款金额(元)',
													dataIndex : 'receiveAmount',
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'receiveAmount',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '剩余应收款(元)',
													dataIndex : 'leftAmount',
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'leftAmount',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '经办人',
													dataIndex : 'operatorName',
													editor : new Ext.grid.GridEditor(new Ext.form.TextField({
														id : 'operatorName',
														allowBlank : false,
														emptyText : '请选择经办人',
														maxLength : 64,
														listeners : {
															focus : function() {
																UserSelector.getView(function(ids, names) {
																	Ext.getCmp("operatorName").setValue(names);
																	Ext.getCmp("operatorId").setValue(ids);
																}, true).show();
															}
														}
													}))
												}, {
													dataIndex:'operatorId',
													width : 0,
													editor : new Ext.grid.GridEditor(new Ext.form.TextField({
														id : 'operatorId',
														maxLength : 64
													}))
												}, {
													header : '备注',
													dataIndex : 'remark',
													editor : new Ext.grid.GridEditor(new Ext.form.TextField({
														id : 'remark'
													})),
													width : 200
												}],
										defaults : {
											sortable : false,
											menuDisabled : false,
											width : 100
										}
									}),
									tbar : new Ext.Toolbar({
										height : 30,
										items : [{
													iconCls : 'btn-add',
													text : '添加',
													xtype : 'button',
													handler : function() {
														var DataRecord = Ext.data.Record.create([{
																	name : 'id'
																}, {
																	name : 'billDate'
																}, {
																	name : 'billAmount'
																}, {
																	name : 'receiveDate'
																}, {
																	name : 'receiveAmount'
																}, {
																	name : 'leftAmount'
																}, {
																	name : 'operatorId'
																}, {
																	name : 'remark'
																}, {
																	name : 'operatorName'
																}]);
														var store = Ext.getCmp('projectReceive.resultGridDataGrid').store;
														var grid = Ext.getCmp('projectReceive.resultGridDataGrid');

														var n1 = '';

														var newRowData = {
															billDate : n1,
															billAmount : n1,
															receiveDate : n1,
															receiveAmount : n1,
															leftAmount : n1,
															remark:n1,
															operatorName:n1,
															operatorId:n1
														};
														var newRecord = new DataRecord(newRowData);
														store.add([newRecord]);

														grid.getSelectionModel().on('selectionchange', function(sm) {
															Ext.getCmp('projectReceive.removeBtn').setDisabled(sm.getCount() < 1);
														});
													}
												}, {
													iconCls : 'btn-del',
													text : '删除',
													id : 'projectReceive.removeBtn',
													xtype : 'button',
													handler : function() {
														var store = Ext.getCmp('projectReceive.resultGridDataGrid').store;
														var grid = Ext.getCmp('projectReceive.resultGridDataGrid');
														var s = grid.getSelectionModel().getSelections();
														for (var i = 0, r; r = s[i]; i++) {
															store.remove(r);
														}
														store.fireEvent("update");//更新事件
													}
												}]
									})
								}]
					}, {
						xtype : 'textfield',
						hidden : true,
						validator : function() {
							var receiveRegInfoDataList = Ext.getCmp('receiveRegInfoDataList').getValue();
							var errorLabel = Ext.getCmp("projectReceiveErrorLabel");
							if (Ext.isEmpty(thizId)) {
								if (Ext.isEmpty(receiveRegInfoDataList)) {//为空显示提示
									errorLabel.setText('请填写收款详情');
									return false;
								}
							}
							return true
						}
					}

			]
		});
		//加载表单对应的数据	
		this.initData();
		//初始化功能按钮
		this.buttons = [{
					text : '保存',
					iconCls : 'btn-save',
					handler : this.save.createCallback(this.formPanel, this)
				}, {
					text : '重置',
					iconCls : 'btn-reset',
					handler : this.reset.createCallback(this.formPanel)
				}, {
					text : '取消',
					iconCls : 'btn-cancel',
					handler : this.cancel.createCallback(this)
				}];
	},//end of the initcomponents
	/**
	 * 初始化数据
	 * 
	 * @param {}
	 *            formPanel
	 */
	initData : function() {
		//加载表单对应的数据	
		if (this.id != null && this.id != 'undefined') {
			Ext.getCmp('projectReceive.resultGridDataGrid').getStore().load({params:{
					'Q_projectReceive.id_L_EQ':this.id,
					start:0,
					limit:9999
			}});
			this.formPanel.getForm().load({
				deferredRender : false,
				url : __ctxPath + '/project/getProjectReceive.do?id=' + this.id,
				waitMsg : '正在载入数据...',
				success : function(form, action) {
					var jsonData = Ext.util.JSON.decode(action.response.responseText);
					var res = jsonData.data;
					if (!Ext.isEmpty(res.project)) {
						Ext.getCmp("projectReceiveProName").setValue(res.project.proName);
						Ext.getCmp("projectReceiveProName").originalValue = res.project.proName;
						Ext.getCmp("projectReceive.project.id").setValue(res.project.id);
						Ext.getCmp("projectReceive.project.id").originalValue = res.project.id;
						Ext.getCmp("projectReceiveContractAmount").setValue(res.project.contractAmount);
						Ext.getCmp("projectReceiveContractAmount").originalValue = res.project.contractAmount;
					}
					//Ext.getCmp("").originalValue=
				},
				failure : function(form, action) {
				}
			});
		}
	},
	/**
	 * 重置
	 * 
	 * @param {}
	 *            formPanel
	 */
	reset : function(formPanel) {
		formPanel.getForm().reset();
	},
	/**
	 * 取消
	 * 
	 * @param {}
	 *            window
	 */
	cancel : function(window) {
		window.close();
	},
	/**
	 * 保存记录
	 */
	save : function(formPanel, window) {
		if (formPanel.getForm().isValid()) {
			formPanel.getForm().submit({
				method : 'POST',
				waitMsg : '正在提交数据...',
				success : function(fp, action) {
					Ext.ux.Toast.msg('操作信息', '成功保存信息！');
					var gridPanel = Ext.getCmp('ProjectReceiveGrid');
					if (gridPanel != null) {
						gridPanel.getStore().reload();
					}
					window.close();
				},
				failure : function(fp, action) {
					Ext.MessageBox.show({
						title : '操作信息',
						msg : '信息保存出错，请联系管理员！',
						buttons : Ext.MessageBox.OK,
						icon : Ext.MessageBox.ERROR
					});
//					window.close();
				}
			});
		}
	}//end of save

});